﻿using UnityEngine;
using System.Collections;
using Assets.Game.scripts.ui.models;
using Game.Scripts.Managers;
using FrenzyIsland.UI;

[RequireComponent(typeof(BuildingWidgetModel))]
public class BuildingWidgetController : MonoBehaviour {

    public UIGrid buildingGrid;
    public GameObject buildingItemRenderer;
    public UIScrollView scrollview;

    private bool requireRefresh = false;

    public void Start() {
        BuildingWidgetModel model = this.GetComponent<BuildingWidgetModel>();

        if (this.buildingGrid != null && this.buildingItemRenderer != null) {
            foreach (BuildingPrototype prototype in model.buildingManager.prototypes) {

                GameObject itemRendererInstance = NGUITools.AddChild(this.buildingGrid.gameObject, this.buildingItemRenderer);

                //assegno il model per i binding
                BuildingPrototypeItemRendererModel itemRendererModel = itemRendererInstance.GetComponent<BuildingPrototypeItemRendererModel>();
                if (itemRendererModel != null) {
                    itemRendererModel.prototype = prototype;
                }

                //assegno il click 
                UIButton btn = itemRendererInstance.GetComponent<UIButton>();
                EventDelegate ed = new EventDelegate(this, "onSelectedBuilding");
                ed.parameters[0].value = itemRendererInstance;
                btn.onClick.Add(ed);

            }
        }

        requireRefresh = true;
    }

    public void Update()
    {
        if( requireRefresh )
        {
            if (scrollview != null)
            {
                scrollview.ResetPosition();
                scrollview.UpdatePosition();
            }
            else
                Debug.LogError("scrollview is null");

            requireRefresh = false;
        }
    }

    public void onClose() {
        NGUITools.Destroy(this.gameObject);
        print("exiting building widget");
    }

    public void onSelectedBuilding(GameObject selectedObject) {

        GuiManager guiManager = UIRoot.list[0].GetComponent<GuiManager>();
        BuildingPrototypeItemRendererModel itemRendererModel = selectedObject.GetComponent<BuildingPrototypeItemRendererModel>();

        if (itemRendererModel != null) {

            //istanzio un modello di preview
            GameObject buildingPreview = BuildingManager.instance.StartBuildingMode(itemRendererModel.prototype);

            if ( buildingPreview != null )
            {
                //aggiungo al nuovo gameobject il controllore per creare il building
                BuildingPreviewController.SetComponent(buildingPreview);

                //chiudo il widget, e passo la palla al componente creato
                guiManager.CloseWidget(this.gameObject);
            }
        }

        
    }
    
}
